<template>
  <el-dialog
    title="绑定健康卡"
    :visible="value"
    width="400px"
    custom-class="dialog-box"
    @close="onClose"
    @open="onOpen"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <el-form
      @submit.native.prevent="onSubmit"
      label-width="100px"
      label-position="top"
      ref="form"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="健康卡号：">
        <el-input v-model="form.cardNumber" maxlength="50" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="健康卡秘钥：">
        <el-input v-model="form.secretKey" maxlength="50" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: ["value", "curItem"],
  data() {
    return {
      form: {
        cardNumber: "",
        secretKey: "",
        patientId:''
      },
      rules: {
        cardNumber: [
          { required: true, message: "请输入健康卡号", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "请输入50位以内的健康卡号",
            trigger: "blur"
          }
        ],
        secretKey: [
          { required: true, message: "请输入健康卡秘钥", trigger: "blur" }
        ]
      },
      btnLoading:false
    };
  },
  methods: {
    onOpen() {
      let th=this;
      th.$nextTick(function(){
        if(th.curItem){
          th.form.cardNumber=th.curItem.healthCard
          th.form.secretKey=th.curItem.healthActivationCode
        }
      })
    },
    onClose() {
      let th=this;
      th.$emit("input",false)
      th.$emit("success")
    },
    onSubmit() {
      const th = this;
      let j = {};
      const fn = function() {
        Object.assign(j, th.form);
        j.patientId=th.curItem.patientId;
        th.btnLoading = true;
        th.$api.patientRelevanceCard(j).then(res => {
            if (res.executed) {
              th.$message.success("关联健康卡成功");
              th.$emit("success");
              th.onClose();
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(res => {
            th.btnLoading = false;
          });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          Object.assign(j, th.form);
          fn();
        }
      });
    }
  }
};
</script>